import request from '@/utils/request'
import {fetchEventSource} from "@microsoft/fetch-event-source";
import {getToken} from "@/utils/auth";

// 查询AI 聊天消息列表
export function listAiChatMessage(query) {
  return request({
    url: '/ai/aiChatMessage/list',
    method: 'get',
    params: query
  })
}

// 查询AI 聊天消息详细
export function getAiChatMessage(id) {
  return request({
    url: '/ai/aiChatMessage/' + id,
    method: 'get'
  })
}

// 新增AI 聊天消息
export function addAiChatMessage(data) {
  return request({
    url: '/ai/aiChatMessage',
    method: 'post',
    data: data
  })
}

// 修改AI 聊天消息
export function updateAiChatMessage(data) {
  return request({
    url: '/ai/aiChatMessage',
    method: 'put',
    data: data
  })
}

// 删除AI 聊天消息
export function delAiChatMessage(id) {
  return request({
    url: '/ai/aiChatMessage/' + id,
    method: 'delete'
  })
}


export function sendChatMessageCall(data) {
  return request({
    url: '/ai/aiChatMessage/send-call',
    method: 'post',
    data: data
  })
}

const baseUrl = import.meta.env.VITE_APP_BASE_API;

export async function sendChatMessageStream (
  conversationId,
  content,
  ctrl,
  enableContext,
  onMessage,
  onError,
  onClose
){
  const token = getToken()
  return fetchEventSource(baseUrl+`/ai/aiChatMessage/send-stream`, {
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`
    },
    openWhenHidden: true,
    body: JSON.stringify({
      conversationId,
      content,
      useContext: enableContext
    }),
    onmessage: onMessage,
    onerror: onError,
    onclose: onClose,
    signal: ctrl.signal
  })
}
